var MJModel           = require('./MJModel');
let roomAPI           = require('../../API/RoomAPI');
var MJProto           = require('./MJProto');
var RoomProto         = require('../../API/RoomProto');
var HallApi           = require('../../API/HallAPI');
var RoomAPI           = require('../../API/RoomAPI');
var enumeration       = require('../../Constant/enumeration');
var RoomMessageRouter = 'game.gameHandler.roomMessageNotify';
var GameMessageRouter = 'game.gameHandler.gameMessageNotify';

cc.Class({
	extends: cc.Component,
	properties: {
		bureauLabel: cc.Label,
		roomIDLabel: cc.Label,
		readyButton: cc.Node,
		backhallButton: cc.Node,
	},

	onLoad: function () {
		MJModel.init();
		Global.MessageCallback.addListener('RoomMessagePush', this);
		Global.MessageCallback.addListener('GameMessagePush', this);
		Global.MessageCallback.addListener('ReConnectSuccess', this);
        Global.MessageCallback.addListener('GAME_EVENT', this);
        Global.MessageCallback.addListener('UpdateGameBg', this);
		/* 获取场景 */
        this.scheduleOnce(function () {
            RoomAPI.roomMessageNotify(RoomProto.getRoomSceneInfoNotify());
        }, 0.2);
		this.updateBgSprite();
		if (cc.sys.localStorage.getItem('gameMusic') == "gameMusic2") {
			Global.AudioManager.startPlayBgMusic("Game/Common/Audio/game_bg_2");
		}
		else {
			Global.AudioManager.startPlayBgMusic("Game/Common/Audio/game_bg_1");
		}
		if (Global.Constant.development) {
			cc.find('Test', this.node).active = true;
		}
	},

	/*
	 * 游戏初始化
	 * 断线重连
	 */
	gameInit: function () {
		this.setHeadAndCard();
		this.bureauLabel.string = '第'+MJModel.getCurBureau()+'/'+MJModel.getMaxBureau()+'局';
		this.roomIDLabel.string = '房号：'+MJModel.getRoomID();
		this.setReadyAndBackButton();
		if (Global.DialogManager.isDialogExit('Game/Majiang/MJResultDialog')) {
			Global.DialogManager.destroyDialog('Game/Majiang/MJResultDialog');
		}
		cc.find('Tip', this.node).active = false;
		let operateRecord = MJModel.getOperateRecord();
		let lastOperate = operateRecord[operateRecord.length-1];
		let myChairID = MJModel.getMyChairID();
		if (lastOperate && lastOperate == myChairID && lastOperate.operate == MJProto.operateType.PENG) {
			let operateArray = MJModel.getOperateArrayByChairID(myChairID);
			if (msg.data.operateArray.indexOf(MJProto.operateType.QI) != -1) {
				cc.find('Tip', this.node).active = true;
			} 
		}
		cc.find('Tuoguan', this.node).active = MJModel.getIsTrust();
	},

	messageCallbackHandler: function(router, msg) {
		if(!MJModel.getGameInited()) { return; }
		if (router === 'RoomMessagePush') {
			if(msg.type === RoomProto.GET_ROOM_SCENE_INFO_PUSH) {
				console.log('gameInit=============================');
				this.gameInit();
			}
			else if(msg.type === RoomProto.USER_LEAVE_ROOM_RESPONSE) {
			}
			else if(msg.type === RoomProto.OTHER_USER_ENTRY_ROOM_PUSH) {
				/* this.showHeadNode(msg.data.roomUserInfo.chairID); */
			}
			else if(msg.type === RoomProto.USER_LEAVE_ROOM_PUSH) {
				if(msg.data.roomUserInfo.chairID == MJModel.getMyChairID()) {
					this.enterHall();
				}
			}
			else if(msg.type === RoomProto.USER_READY_PUSH) {
				this.setReadyAndBackButton();
			}
			else if(msg.type === RoomProto.GAME_END_PUSH) {
			}
			else if(msg.type === RoomProto.ROOM_DISMISS_PUSH) {
			}
			else if(msg.type === RoomProto.ASK_FOR_DISMISS_PUSH) {
				if (!Global.DialogManager.isDialogExit('Game/DismissNode')) {
					msg.data.myChairID = MJModel.getMyChairID();
					Global.DialogManager.createDialog('Game/DismissNode', msg.data, function (dialog) {
						Global.DialogManager.removeLoadingCircle();
					});
				}
			}
			else if(msg.type === RoomProto.USER_CHANGE_SEAT_PUSH) {
				let user = MJModel.getUserByChairID(MJModel.getMyChairID());
				if (MJModel.getGameStatus() == MJProto.gameStatus.NONE && !(user.userStatus&RoomProto.userStatusEnum.READY) && MJModel.getMyChairID() < MJModel.getChairCount()) {
					this.readyButton.active = true;
				}
				else {
					this.readyButton.active = false;
				}
				cc.find('Pangguan', this.node).active = (MJModel.getMyChairID() >= MJModel.getChairCount());
			}
			else if(msg.type === RoomProto.USER_CHAT_PUSH) {
				this.onChat(msg.data.fromChairID, msg.data.toChairID, msg.data.msg);
			}
		}
		else if(router === 'GameMessagePush') {
			if(msg.type === MJProto.GAME_BUREAU_PUSH) {
				this.bureauLabel.string = '局数：'+MJModel.getCurBureau()+'/'+MJModel.getMaxBureau();
			}
			else if(msg.type === MJProto.GAME_STATUS_PUSH) {
				this.setReadyAndBackButton();
			}
			else if(msg.type === MJProto.GAME_TURN_OPERATE_PUSH) {
					cc.find('Tip', this.node).active = false;
			}
			else if(msg.type === MJProto.GAME_TURN_PUSH) {
				let operateRecord = MJModel.getOperateRecord();
				let lastOperate = operateRecord[operateRecord.length-1];
				if (lastOperate && lastOperate.operate == MJProto.operateType.PENG) {
					if (msg.data.chairID == MJModel.getMyChairID() && msg.data.operateArray.indexOf(MJProto.operateType.QI) != -1) {
						cc.find('Tip', this.node).active = true;
					} 
				}
			}
			else if(msg.type === MJProto.GAME_END_PUSH) {
				if (msg.data.result.length > 0) {
					msg.data.enterHall = this.enterHall.bind(this);
					msg.data.mjMainDialog = this;
					msg.data.isBureauFull = (MJModel.getCurBureau() == MJModel.getMaxBureau());
					/* Global.DialogManager.createDialog('Game/Majiang/MJResult', msg.data, function (dialog) {
						Global.DialogManager.removeLoadingCircle();
					}); */
				}
				else {
					this.enterHall();
				}
			}
			else if(msg.type === MJProto.GAME_TRUST_PUSH) {
				if (msg.data.chairID == MJModel.getMyChairID()) {
					cc.find('Tuoguan', this.node).active = msg.data.trust;
				}
			}
			else if(msg.type === MJProto.GAME_REVIEW_PUSH) {
				let reviewRecord = MJModel.getReviewRecord();
				if (reviewRecord && reviewRecord.length > 0) {
					/* Global.DialogManager.createDialog("Game/Majiang/MJReviewDialog"); */
					Global.DialogManager.createDialog("Game/Majiang/MJReviewResult", {
						reviewRecord: reviewRecord,
					});
				}
				else {
					Global.DialogManager.addTipDialog('没有数据');
				}
			}
			else if(msg.type === MJProto.GAME_RESULT_PUSH) {
				msg.data.enterHall = this.enterHall.bind(this);
				msg.data.mjMainDialog = this;
				msg.data.isBureauFull = (MJModel.getCurBureau() == MJModel.getMaxBureau());
				Global.DialogManager.createDialog("Game/Majiang/MJResultDialog", msg.data, function () {
					Global.DialogManager.removeLoadingCircle();
				});
			}
			else if(msg.type == MJProto.GAME_DISMISS_PUSH) {
				if (msg.data.userArray) {
					this.showMJAllResultFunc = () => {
						this.showMJAllResultFunc = null;
						msg.data.isUnionCreate = MJModel.isUnionCreate();
						msg.data.isBureauFull = (MJModel.getCurBureau() == MJModel.getMaxBureau());
						msg.data.enterHall = this.enterHall.bind(this);
						// msg.data.roomDismissReason = MJModel.getRoomDismissReason();
						msg.data.roomDismissReason = msg.data.reason;
						Global.DialogManager.createDialog('Game/Majiang/MJAllResult', msg.data, function (dialog) {
							Global.DialogManager.removeLoadingCircle(); 
						});
					};
					if (msg.data.reason != enumeration.gameRoomDismissReason.BUREAU_FINISHED) {
						this.showMJAllResultFunc();
					}
				}
				else {
					this.enterHall();
				}
			}
		}
		else if(router === 'ReConnectSuccess' || (router == 'GAME_EVENT' && msg == cc.game.EVENT_SHOW)) {
			if(Global.UserModel.isInRoom()) {
				Global.API.hall.joinRoomRequest(MJModel.getRoomID(), function() {
					MJModel.setGameInited(false);
					roomAPI.roomMessageNotify(RoomProto.getRoomSceneInfoNotify());
				}, function () {
					this.enterHall();
				}.bind(this));
			} else {
				this.enterHall();
			}
		}
		else if(router == 'UpdateGameBg') {
			this.updateBgSprite();
		}
	},

	onReadyClick: function (event, param) {
        Global.AudioManager.playCommonSoundClickButton();
		if(!MJModel.getGameInited()) { return; }
		Global.NetworkManager.notify(RoomMessageRouter, RoomProto.userReadyNotify(true));
		this.readyButton.active = false;
	},

	onExitClick: function (event, param) {
        Global.AudioManager.playCommonSoundClickButton();
		if(!MJModel.getGameInited()) { return; }
		if (param != 'backhall') {
			this.onSwitchClick();
		}
		let user = MJModel.getUserByChairID(MJModel.getMyChairID());
		let canDismiss = ((user.userStatus&RoomProto.userStatusEnum.DISMISS) != 0 && user.chairID < MJModel.getChairCount());
		if (canDismiss && MJModel.getGameStarted()) {
			Global.DialogManager.addPopDialog('是否确定发出解散申请？', function() {
				Global.NetworkManager.notify(RoomMessageRouter, RoomProto.getAskForDismissNotifyData(true));
				Global.DialogManager.addLoadingCircle();
			}, function() {});
		}
		else {
			Global.DialogManager.addPopDialog('确认退出游戏?', function() {
				Global.NetworkManager.notify(RoomMessageRouter, RoomProto.userLeaveRoomNotify());
				Global.DialogManager.addLoadingCircle();
			}, function() {});
		} 
	},

	onSettingClick: function () {
        Global.AudioManager.playCommonSoundClickButton();
		if(!MJModel.getGameInited()) { return; }
		Global.DialogManager.createDialog("UI/Setting/SettingDialog");
		// this.onSwitchClick();
	},

	onSwitchClick: function () {
        Global.AudioManager.playCommonSoundClickButton();
		if(!MJModel.getGameInited()) { return; }
		// let user = MJModel.getUserByChairID(MJModel.getMyChairID());
		// let canDismiss = ((user.userStatus&RoomProto.userStatusEnum.DISMISS) != 0 && user.chairID < MJModel.getChairCount());
		// let sprite = cc.find('Setting/bg/DismissButton/Sprite', this.node).getComponent(cc.Sprite);
		// if (canDismiss && MJModel.getGameStarted()) {
			// Global.CCHelper.updateSpriteFrame('Game/Glob/dismiss', sprite);
		// }
		// else {
			// Global.CCHelper.updateSpriteFrame('Game/Glob/leaveroom', sprite);
		// }

		/* let bg = cc.find('Setting/bg', this.node);
		let url = 'Game/Glob/button1';
		let node = cc.find('Setting/Button/Background', this.node);
		if (!bg.active) {
			url = 'Game/Glob/button2';
			bg.active = true;
			Global.CCHelper.updateSpriteFrame(url, node.getComponent(cc.Sprite));
		}
		else {
			Global.CCHelper.updateSpriteFrame(url, node.getComponent(cc.Sprite));
			bg.active = false;
		} */
		let setingPanel = cc.find("SettingMenu", this.node);
		if (setingPanel) {
			setingPanel.active = true;
		}
	},

	onCloseSettingPanel: function () {
		let setingPanel = cc.find("SettingMenu", this.node);
		if (setingPanel) {
			setingPanel.active = false;
		}
	},

	onRefrush: function (event) {
		Global.AudioManager.playCommonSoundClickButton();
		if(!MJModel.getGameInited()) { return; }
		if (event.target.lastClick && Date.now()-event.target.lastClick < 10*1000) {
			Global.DialogManager.addTipDialog('请勿频繁操作');
			return;
		}
		Global.DialogManager.addTipDialog('刷新界面可以修复游戏显示问题');
		event.target.lastClick = Date.now();
		console.clash("majiang-onRefrush", MJModel.getRoomData());
		this.messageCallbackHandler('ReConnectSuccess');
	},

	onDestroy: function () {
		Global.MessageCallback.removeListener('RoomMessagePush', this);
		Global.MessageCallback.removeListener('GameMessagePush', this);
		Global.MessageCallback.removeListener('ReConnectSuccess', this);
        Global.MessageCallback.removeListener('GAME_EVENT', this);
        Global.MessageCallback.removeListener('UpdateGameBg', this);
	},

	updateBgSprite: function () {
		let bgUrl = cc.sys.localStorage.getItem('gameBg');
		/* TODO 底纹 */
		/* let title = (bgUrl == 'gameBg1')? 'Game/Niuniu/niuniudiwen':'Game/Niuniu/niuniudiwen1'; */
		bgUrl = (!bgUrl || bgUrl == 'gameBg1')? 'Game/Common/beijinglan':'Game/Common/beijinglv';
		/* Global.CCHelper.updateSpriteFrame(title, cc.find('background/diwen', this.node).getComponent(cc.Sprite)); */
		Global.CCHelper.updateSpriteFrame(bgUrl, cc.find('background', this.node).getComponent(cc.Sprite));
	},

	setHeadAndCard: function () {
		if (MJModel.getChairCount() != 2) {
			for (let i = 0; i < 4; ++i) {
				let head = cc.find('Head'+(i+1), this.node);
				head.getComponent('MJHead').setIndex(i);
				this.addHeadClickEvent(cc.find('msgbg', head));
			}
		}
		else {
			let head1 = cc.find('Head1', this.node);
			head1.getComponent('MJHead').setIndex(0);
			this.addHeadClickEvent(cc.find('msgbg', head1));
			let head2 = cc.find('Head3', this.node);
			head2.getComponent('MJHead').setIndex(2);
			this.addHeadClickEvent(cc.find('msgbg', head2));
		}
	},

	addHeadClickEvent: function (node) {
		node.on(cc.Node.EventType.TOUCH_START, () => {
			if (node.lastClick && Date.now()-node.lastClick < 500) { /* 防止重复点击 */ 
				return;
			}
			node.lastClick = Date.now();
			let logic = node.parent.getComponent('MJHead');
			let user = MJModel.getUserByChairID(logic.getChairID());
			let address = null;
			try { address = JSON.parse(user.userInfo.address); } catch(e) {}
			let params = {
				fromChairID: MJModel.getMyChairID(),
				toChairID: logic.getChairID(),
				avatar: user.userInfo.avatar,
				id: user.userInfo.uid,
				ip: user.userInfo.lastLoginIP,
				location: user.userInfo.location,
				x: address? address.x:'未知',
				y: address? address.y:'未知',
				gold: user.userInfo.score,
				name: user.userInfo.nickname,
			};
			Global.DialogManager.createDialog('Chat/HeadDetail', params);
		}, this);
	},

	setReadyAndBackButton: function () {
		this.readyButton.active = false;
		if (MJModel.getGameStatus() == MJProto.gameStatus.NONE) {
			let user = MJModel.getUserByChairID(MJModel.getMyChairID());
			if ((user.userStatus&RoomProto.userStatusEnum.READY) == 0) {
				this.readyButton.active = true;
			}
		}
		this.backhallButton.active = false;
		if (MJModel.getGameStatus() == MJProto.gameStatus.NONE && MJModel.getCurBureau() == 0) {
			this.backhallButton.active = true;
		}
	},

	enterHall: function () {
		if(!MJModel.getGameInited()) { return; }
		let isUnionCreate = MJModel.isUnionCreate();
		Global.DialogManager.destroyDialog('Game/Majiang/MJMainDialog');
		if (isUnionCreate) {
			Global.DialogManager.createDialog("UI/Union/UnionMain/UnionMainDialog", {unionID: MJModel.getRoomCreator().unionID});
		}
		else {
			Global.DialogManager.createDialog('UI/Hall/HallDialog', null, function () {
				Global.DialogManager.removeLoadingCircle();
			});
		}
	},

	onTrustClick: function () {
		Global.AudioManager.playCommonSoundClickButton();
		if(!MJModel.getGameInited()) { return; }
		Global.NetworkManager.notify(GameMessageRouter, MJProto.gameTrushNotify(true));
	},

	onCancelTuoguan: function () {
		Global.AudioManager.playCommonSoundClickButton();
		if(!MJModel.getGameInited()) { return; }
		Global.NetworkManager.notify(GameMessageRouter, MJProto.gameTrushNotify(false));
	},

	onRuleClick: function () {
		Global.AudioManager.playCommonSoundClickButton();
		if(!MJModel.getGameInited()) { return; }
		let node = cc.find('RuleButton', this.node);
		if (node.lastClick && Date.now()-node.lastClick < 500) { /* 防止重复点击 */ 
			return;
		}
		node.lastClick = Date.now();
		Global.DialogManager.createDialog('Game/RuleNode', this.getRule());
	},

	getRule: function () {
		let gameRule = MJModel.getGameRule();
		let rule = {
			'玩法：': ['', '4个红中', '8个红中'][gameRule.gameFrameType],
			'扎码：': gameRule.ma+'个',
			'托管：': (gameRule.trustTm == 0)? '无':gameRule.trustTm+'秒',
			'高级：': ((gameRule.qidui)? '七对':'') + ((gameRule.chunniunai)? ' 纯牛奶':''),
		};
		if (rule['高级：'].length == 0) {
			rule['高级：'] = '无';
		}
		return rule;
	},

	onReview: function () {
		Global.AudioManager.playCommonSoundClickButton();
		if(!MJModel.getGameInited()) { return; }
		let reviewRecord = MJModel.getReviewRecord();
		let needGet = true;
		if (reviewRecord && reviewRecord.length == MJModel.getCurBureau()) {
			needGet = false;
		}
		if (reviewRecord && MJModel.getGameStatus() == MJProto.gameStatus.PLAYING && reviewRecord.length == MJModel.getCurBureau()-1) {
			needGet = false;
		}
		if (needGet) {
			Global.NetworkManager.notify(GameMessageRouter, MJProto.gameReviewNotify());
		}
		else {
			if (reviewRecord && reviewRecord.length > 0) {
				/* Global.DialogManager.createDialog("Game/Majiang/MJReviewDialog"); */
				Global.DialogManager.createDialog("Game/Majiang/MJReviewResult", {
					reviewRecord: reviewRecord,
				});
			}
			else {
				Global.DialogManager.addTipDialog('没有数据');
			}
		}
	},
});
